<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2021/7/6
 * Time: 5:19 下午
 */

namespace app\admin\validator;


use app\lib\BaseValidator;
use app\lib\exception\ParamsException;
use app\utils\RsaUtils;
use Carbon\Carbon;
use think\facade\Cache;

class LoginValidator extends BaseValidator
{
    protected $rule = [
        'username'      => 'require|alphaDash|length:4,20',
        'password'      => 'require|length:6,20',
        'captcha'       => 'require|length:5',
        'captcha_token' => 'require|vcaptcha'
    ];

    protected $message = [
        'username.require'   => '用户名必填',
        'username.alphaDash' => '用户名只能为数字、字母、减号或下划线',
        'username.length'    => '用户名长度4-20字',
        'password.require'   => '密码必填',
        'password.length'    => '密码长度最少6位,最多20位',
        'captcha'            => '验证码不正确',
        'captcha_token'      => '验证码不正确'
    ];

    // 校验验证码
    protected function vcaptcha ($value, $rule, $data = []): bool {
        $captcha = Cache::store('redis')->get($value);
        if (empty($captcha)) {
            return false;
        }
        if (empty($captcha) || empty($captcha['code']) || !isset($captcha['times'])) {
            return false;
        }
        if (strtolower($captcha['code']) != strtolower($data['captcha'])) {
            $times = $captcha['times'];
            $times += 1;
            if ($times >= 5) {
                Cache::store('redis')->delete($value);
            } else {
                $captcha['times'] = $times;
                $ttl = Cache::store('redis')->handler()->ttl($value);
                if ($ttl > 1) {
                    Cache::store('redis')->set($value, $captcha, $ttl);
                }
            }
            return false;
        }
        Cache::store('redis')->delete($value);
        return true;
    }
}
